<script setup>
import {getSurveysStatusText} from "../../utils/CommonsUtil.js";
import {useRouter} from "vue-router";
import {onMounted, ref} from "vue";
import {off} from "@arco-design/web-vue/es/_utils/dom.js";
import {getSurveysListApi, updateSurveysApi} from "../../apis/SurveysApi.js";
import {Message} from "@arco-design/web-vue";
import {addUserApi, deleteUserApi, getUserListApi, updateUserApi} from "../../apis/UserApi.js";
import {BASE_URL} from "../../config/index.js";

const router = useRouter()
const userList = ref([])
const searchInput = ref('')
const formRef = ref()
const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0, // 总条数初始为0
    showTotal: true, // 显示总数
    showPageSize: true, // 显示页码切换器
    showJumper: true, // 显示快速跳转
});
const isUpdate = ref(false)
const isShowConfig = ref(false)
const form = ref({})
const dataLoading = ref(false);
// 修改后的获取数据方法
const getUserList = async () => {

    dataLoading.value = true
    const res = await getUserListApi(pagination.value.current, pagination.value.pageSize, searchInput.value)
    if (res.code === 0) {
        userList.value = res.data.records
        pagination.value.total = Number(res.data.total)
    } else {
        Message.error(res.message)
    }
    dataLoading.value = false
}
// 处理分页变化事件
const handlePageChange = (current) => {
    pagination.value.current = current
    getUserList()
}
const handleEdit = (data) => {
    form.value = JSON.parse(JSON.stringify(data))
    isShowConfig.value = true
    form.value.userPassword = ''
    isUpdate.value = true
};

const saveConfig = async () => {
    //校验
    formRef.value.validate()
    if (!isUpdate.value){
        //请求
        const res = await addUserApi(form.value)
        if (res.code === 0) {
            Message.success('保存成功')
            isShowConfig.value = false
            await getUserList()
            return true
        } else {
            Message.error(res.message)
            return false
        }
    }else{
        //请求
        const res = await updateUserApi(form.value)
        if (res.code === 0) {
            Message.success('保存成功')
            isShowConfig.value = false
            await getUserList()
            return true
        } else {
            Message.error(res.message)
            return false
        }
    }
};

const createUser = async () => {
    form.value = {}
    isShowConfig.value = true
    form.value.userPassword = ''
    isUpdate.value = false
}

const handleDelete = async (id) => {
    const res = await deleteUserApi(id)
    if (res.code === 0) {
        Message.success('删除成功')
        await getUserList()
    } else {
        Message.error(res.message)
    }
}

// 处理每页数量变化事件
const handlePageSizeChange = (pageSize) => {
    pagination.value.pageSize = pageSize
    getUserList()
}
const uploadSuccess = (res) => {
    form.value.userAvatar = res.response.data.url
}
const removeUpload = (file) => {
    form.value.userAvatar = ''
    return true
}


onMounted(async () => {
    await getUserList()
})
</script>

<template>
    <div class="py-8 px-24">
        <div>
            <a-button type="primary" @click="createUser">创建用户</a-button>

            <a-input-search @search="getUserList" v-model="searchInput" class="ml-8" :style="{width:'360px'}"
                            placeholder="搜索账号或用户名" search-button>
                <template #button-icon>
                    <icon-search/>
                </template>
                <template #button-default>
                    搜索
                </template>
            </a-input-search>
        </div>
        <a-table
            :scroll="{x:2000,y:800}"
            bordered
            stripe
            :loading="dataLoading"
            :data="userList"
            :pagination="pagination"
            @page-change="handlePageChange"
            @page-size-change="handlePageSizeChange"
            class="mt-4"
        >
            <template #columns>
                <a-table-column
                    title="用户ID"
                    dataIndex="id"
                    key="id"
                    width="110"
                />
                <a-table-column
                  title="用户账号"
                  dataIndex="userAccount"
                  key="userAccount"
                  width="150"
                />
                <a-table-column
                  title="用户名"
                  dataIndex="userName"
                  key="userName"
                  width="160"
                />
                <a-table-column
                    title="用户角色"
                    dataIndex="userRole"
                    key="userRole"
                    width="100"
                />
                <a-table-column
                    title="用户电话"
                    dataIndex="userPhone"
                    key="userPhone"
                    width="150"
                />
                <a-table-column
                    title="用户邮箱"
                    dataIndex="userEmail"
                    key="userEmail"
                    width="180"
                />

                <a-table-column
                    title="注册时间"
                    dataIndex="createTime"
                    key="createTime"
                    width="180"
                />
                <a-table-column
                    title="用户头像"
                    dataIndex="userAvatar"
                    key="userAvatar"
                    width="310"
                />

                <a-table-column
                  title="用户简介"
                  dataIndex="userProfile"
                  key="userProfile"
                />

                <!-- 操作列 -->
                <a-table-column
                    title="操作"
                    :width="150"
                    fixed="right"
                >
                    <template #cell="{ record }">
                        <a-space>
                            <a-button
                                type="primary"
                                @click="handleEdit(record)"
                            >
                                编辑
                            </a-button>
                            <a-popconfirm content="删除后不可恢复，确认删除吗？"
                                @ok="handleDelete(record.id)">
                                <a-button
                                    type="primary"
                                    status="danger">
                                    删除
                                </a-button>
                            </a-popconfirm>


                        </a-space>
                    </template>
                </a-table-column>
            </template>
        </a-table>
    </div>


    <a-modal unmount-on-close v-model:visible="isShowConfig" :on-before-ok="saveConfig" ok-text="保存">
        <template #title>
            编辑用户信息
        </template>
        <div>
            <a-form ref="formRef" :model="form"  auto-label-width>
                <a-form-item field="userAccount" label="用户账号">
                    <p v-show="isUpdate">{{form.userAccount}}</p>
                    <a-input v-show="!isUpdate" name="account1" autocomplete="off" v-model="form.userAccount" placeholder="请输入用户昵称" />

                </a-form-item>
                <a-form-item field="userName" label="用户昵称"
                             :rules="[{required:true,message:'用户昵称'},{minLength:1,maxLength:20,message:'用户昵称最大20字符'}]">
                    <a-input name="name1" autocomplete="off" v-model="form.userName" placeholder="请输入用户昵称" />
                </a-form-item>
                <a-form-item field="userPassword" label="用户密码">
                    <a-input-password name="pass1" autocomplete="off" v-model="form.userPassword" placeholder="" />
                </a-form-item>
                <a-form-item field="userPhone" label="用户电话">
                    <a-input v-model="form.userPhone" placeholder="" />
                </a-form-item>
                <a-form-item field="userEmail" label="用户邮箱">
                    <a-input v-model="form.userEmail" placeholder="" />
                </a-form-item>
                <a-form-item field="userProfile" label="用户简介">
                    <a-input v-model="form.userProfile" placeholder="" />
                </a-form-item>
                <a-form-item field="userRole" label="账号状态">
                    <a-select v-model="form.userRole" :style="{width:'220px'}">
                        <a-option value="admin" disabled>管理员</a-option>
                        <a-option value="user">普通用户</a-option>
                        <a-option value="ban" :disabled="form.userRole === 'admin'">封禁</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item field="userAvatar" label="用户头像" >
                    <a-image
                        class="rounded-lg"
                        width="180"
                        :src="form.userAvatar"
                    />
                    <a-upload
                        class="ml-4" :limit="1"
                        withCredentials
                        name="file"
                        accept="image/*"
                        :on-before-remove="removeUpload"
                        @success="uploadSuccess"
                        :action="BASE_URL + '/files/upload'"/>
                </a-form-item>
            </a-form>

        </div>
    </a-modal>


</template>

<style scoped>

</style>
